/*
 * File name: ChatActivity.java
 * Description: This class is used to attach activities of chats and library's floors.  
 */

package edu.usc.libtalk;
import org.json.JSONException;
import org.json.JSONObject;

import edu.usc.libtalk.task.GetJSONObjectTask;
import edu.usc.libtalk.utils.ApplicationService;
import edu.usc.libtalk.utils.InternalConstant;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;

public class ChatActivity extends TabActivity implements InternalConstant {
	
	public final static String CHAT_EXTRA_MODE = "edu.usc.libtalk.chatactivity.mode";
	private static final int TEXT_ID = 0;
	private int user_level;
	Intent intent;
	public static Activity chatActivity;
	private static final String TAG = "ChatActivity";
	private int sel_user_level;
	private int sel_user_seat;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Customize menu title 
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        
        setContentView(R.layout.activity_chat);

        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title_signout);
        
        // Get level and seat that the user selected.
        sel_user_level = ApplicationService.getLevel();
        sel_user_seat = ApplicationService.getSeat();  
        
        // Sign out button Handler    	
    	Button signout_bn = (Button) findViewById(R.id.signout_button);
    	signout_bn.setOnClickListener(new OnClickListener() {
    		public void onClick(View v) {
            	if((sel_user_level != -1) && (sel_user_seat != -1))
            	{
            		createDialog().show();
            	} else {
                	ApplicationService.cleanUpLocal();
                	signOutWithEmail(DEFAULT_EMAIL);
                	ApplicationService.inform("Sign out completed");
            	}
    			
    			    			
    		}
    	});            
        
        chatActivity = this;
        
        
        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost();  // The activity TabHost
        TabHost.TabSpec spec;  // Reusable TabSpec for each tab
        Intent intent;  // Reusable Intent for each tab        
       
        // Initialize a TabSpec for each tab and add it to the TabHost
        // Chats tab
        intent = new Intent().setClass(ChatActivity.this, ChatsActivity.class);
        spec = tabHost.newTabSpec("chats").setIndicator("Chats",
                          res.getDrawable(R.drawable.ic_list_icon))
                      .setContent(intent);
        tabHost.addTab(spec);
        
        // Online users tab
        intent = new Intent().setClass(ChatActivity.this, OnLineUsersActivity.class);
        spec = tabHost.newTabSpec("onlineuser").setIndicator("Online",
                          res.getDrawable(R.drawable.ic_globe_icon_bw))
                      .setContent(intent);
        tabHost.addTab(spec);        
        
        // SSL Level 1 tab
        intent = new Intent().setClass(ChatActivity.this, SSL1Activity.class);
        intent.putExtra(CHAT_EXTRA_MODE, "CHAT_MODE");
        spec = tabHost.newTabSpec("ssl1").setIndicator("Level 1",
                          res.getDrawable(R.drawable.ic_library_level))
                      .setContent(intent);
        tabHost.addTab(spec);
 
        // SSL Level 2 tab
        intent = new Intent().setClass(ChatActivity.this, SSL2Activity.class);
        intent.putExtra(CHAT_EXTRA_MODE, "CHAT_MODE");
        spec = tabHost.newTabSpec("ssl2").setIndicator("Level 2",
                          res.getDrawable(R.drawable.ic_library_level))
                      .setContent(intent);
        tabHost.addTab(spec);
 
        // SSL Level 3 tab
        intent = new Intent().setClass(ChatActivity.this, SSL3Activity.class);
        intent.putExtra(CHAT_EXTRA_MODE, "CHAT_MODE");
        spec = tabHost.newTabSpec("ssl3").setIndicator("Level 3",
                          res.getDrawable(R.drawable.ic_library_level))
                      .setContent(intent);
        tabHost.addTab(spec);        
        
        user_level = ApplicationService.getLevel();
        
        if(user_level != -1)
        	tabHost.setCurrentTab(user_level+1); 
        else tabHost.setCurrentTab(1);
        

    }
    
    @Override
    public void onBackPressed()
    {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(ChatActivity.this);
		alertDialog.setTitle("Exit this application");
		alertDialog.setMessage("Are you sure you want to close this application?");
		
		alertDialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				
				//finish();
				
				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);				
			}});
		
		alertDialog.setNegativeButton("Cancel", null);		
		
		alertDialog.show();
    }
           
    /**
     * Create and return an alert dialog with an edit text box.
     */
    private Dialog createDialog() {
 
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Sign out");
        builder.setMessage("Do you want to email your chat messages? If so, input your email: ");
 
         // Use an EditText view to get user input.
         final EditText input = new EditText(this);
         input.setId(TEXT_ID);
         builder.setView(input);
 
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
 
            @Override
            public void onClick(DialogInterface dialog, int whichButton) {
                String email = input.getText().toString();
                
                if(ApplicationService.isEmailValid(email))
                {
                	ApplicationService.cleanUpLocal();
                	signOutWithEmail(email);
                }
                else
                {
                	ApplicationService.inform("Invalid email. Please sign out again");
                }
                
                return;
            }
        });
 
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
 
            @Override
            public void onClick(DialogInterface dialog, int which) {
            	ApplicationService.cleanUpLocal();
            	signOutWithEmail(DEFAULT_EMAIL);
                return;
            }
        });
 
        return builder.create();
    }
    
    private void signOutWithEmail(String email) {
    	
    	intent = new Intent(ChatActivity.this, LibListActivity.class);
    	
    	// Sign out with email    	
    	new GetJSONObjectTask(){
    		@Override
    		protected void onPostExecute(JSONObject result){
				if(result == null){
					ApplicationService.inform(getString(R.string.nointernet));
					finish();
					return;
				}         		
				
				// Parse JSON Object				
                try{
                	int cause = result.getInt("success");                	
                	startActivity(intent);
                	
                }
                catch(JSONException e){
                	Log.e(TAG, "Error parsing data "+e.toString());
                }         		
         	}	
        }.execute(HOSTNAME + SIGN_OUT_URL + "?devicetoken=" + ApplicationService.getDeviceID() + "&email=" + email);	            
    }
    
}
